import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User

from .models import Credential, CredentialImportLog

@csrf_exempt
@require_POST
def save_credentials(request):
    """保存解析的凭证数据"""
    try:
        data = json.loads(request.body)
        credentials_data = data.get('credentials', [])
        file_info = data.get('file_info', {})
        
        if not credentials_data:
            return JsonResponse({'success': False, 'error': '没有可保存的凭证数据'})
        
        # 使用默认用户（如果没有认证系统）
        try:
            user = User.objects.first()  # 或者 request.user if authenticated
        except:
            user = User.objects.filter(is_superuser=True).first()
        
        saved_count = 0
        for cred_data in credentials_data:
            try:
                credential = Credential(
                    location=cred_data.get('location', ''),
                    device_name=cred_data.get('device_name', ''),
                    username=cred_data.get('username', ''),
                    password=cred_data.get('password', ''),
                    url=cred_data.get('url', ''),
                    protocol=cred_data.get('protocol', ''),
                    status=cred_data.get('status', 'normal'),
                    notes=cred_data.get('notes', ''),
                    source_file=file_info.get('file_name', ''),
                    created_by=user
                )
                print(f"收到保存请求，数据条数: {len(credentials_data)}")
                print("第一条数据示例:", credentials_data[0] if credentials_data else "空")
                credential.save()
                saved_count += 1
                
            except Exception as e:
                print(f"保存凭证失败: {str(e)}")
                continue
        
        # 记录导入日志
        import_log = CredentialImportLog.objects.create(
            file_name=file_info.get('file_name', ''),
            file_path=file_info.get('file_path', ''),
            total_count=len(credentials_data),
            success_count=saved_count,
            import_by=user,
            parse_result=data
        )
        
        return JsonResponse({
            'success': True,
            'message': f'成功保存 {saved_count} 条凭证记录',
            'saved_count': saved_count,
            'total_count': len(credentials_data)
        })
        
    except Exception as e:
        return JsonResponse({'success': False, 'error': f'保存失败: {str(e)}'})